package jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JdbcPort {
	// 定义数据库的用户名
	private static final String USERNAME = "root";
	// 定义数据库的密码
	private static final String PASSWORD = "nzzqskfj2020";
	// 定义数据库的驱动信息
	private static final String DRIVER = "com.mysql.jdbc.Driver";
	// 定义访问数据库的地址
	private static final String URL = "jdbc:mysql://localhost:3306/school_library?useUnicode=true&characterEncoding=utf-8&useSSL=false";
	
	private static Connection conn;
	private PreparedStatement pstmt=null;
	private ResultSet rs=null; 

	static{
        try {
            // 加载驱动程序
            Class.forName(DRIVER);
            
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
	public static Connection getConnection() {

		try {
			conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);

		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("Connection exception !");
		}

		return conn;

	}
	
	public static void closeAll(Connection conn,PreparedStatement pre,ResultSet rs)
	{
		try {
			if(rs!=null)
			{
				rs.close();
			}
			if(pre!=null)
			{
				pre.close();
			}
			if(conn!=null)
			{
				conn.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void closeBoth(Connection conn,PreparedStatement pre)
	{
		try {
			
			if(pre!=null)
			{
				pre.close();
			}
			if(conn!=null)
			{
				conn.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public ResultSet execQuery(final String strSQL,final Object[] params){
		conn=getConnection();
		try{
			pstmt=conn.prepareStatement(strSQL);
			for(int i=0;i<params.length;i++){
				pstmt.setObject(i+1, params[i]);
			}
			rs=pstmt.executeQuery();
			return rs;
		} catch(SQLException e){
			e.printStackTrace();
			return null;
		}
	}
	
	public int execIorU(final String sql, final Object[] params) {
		int res=0;
		conn=getConnection();
		try {
			pstmt=conn.prepareStatement(sql);
			for(int i=0;i<params.length;i++) {
				pstmt.setObject(i+1, params[i]);
			}
			res=pstmt.executeUpdate();
		}catch(SQLException e){
			e.printStackTrace();
			return -1;
		}
		return res;
	}
	/*
	 * public static void main(String[] args) {
		try {
			Connection conn = JdbcPort.getConnection();
			if (conn != null) {
				System.out.println("数据库连接正常");
				conn.close();
			} else {
				System.out.println("数据库连接异常");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	 */
	
}
